<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    fullscreen
    @cancel="handleCancel"
    :footer="null"
  >
    <a-spin :spinning="confirmLoading">
      <a-card :bordered="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actCd" label="券编码">
          <span v-if="!model.id">自动生成</span>
          <span v-else>{{ model.actCd }}</span>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actNm" label="券名称">
          <a-input placeholder="" v-model.trim="model.actNm" style="width: 300px" :disabled="readonlyed" />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="selecteddeparts" label="适用门店">
          <a-cascader
            :options="departModel.departTreeOptions"
            @change="onDepartChange"
            :showSearch="true"
            expand-trigger="hover"
            placeholder=""
            :fieldNames="fieldNames"
            style="width: 300px"
            v-model="model.selecteddeparts"
            :disabled="readonlyed"
          />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="couponType" label="券类型">
          <a-radio-group name="couponType" v-model="model.couponType" :disabled="readonlyed">
            <a-radio value="mj"> 满减 </a-radio>
            <a-radio value="zk"> 折扣 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ruleVal" label="优惠内容">
          <div v-if="model.couponType == 'zk'">
            打
            <a-input-number
              placeholder="1-9.9之间"
              v-model.trim="model.ruleVal"
              :min="1"
              :max="9.9"
              defaultValue="1"
              :disabled="readonlyed"
            />
            折
          </div>
          <div v-if="model.couponType == 'mj'">
            减免
            <a-input-number
              placeholder=""
              v-model.trim="model.ruleVal"
              :min="1"
              :max="999999"
              defaultValue="1"
              :disabled="readonlyed"
            />
            元
          </div>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lessMoney" label="使用门槛">
          满
          <a-input-number
            placeholder=""
            v-model.trim="model.lessMoney"
            :min="1"
            :max="999999"
            default-value="1"
            :disabled="readonlyed"
          />
          元可用
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="distTotal" label="发券总量">
          <a-input-number v-model="model.distTotal" :disabled="!isEdit" min="1" />
        </a-form-model-item>
        <a-form-model-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          prop="reduceMax"
          label="优惠上限(元)"
          v-show="false"
        >
          <a-input-number
            placeholder=""
            v-model.trim="model.reduceMax"
            :min="0"
            :max="999999"
            defaultValue="0"
            :disabled="!isEdit"
          />
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exipreType" label="有效期">
          <a-radio-group name="exipreType" v-model="model.exipreType" :disabled="!isEdit">
            <a-radio value="fix_date" :style="radioStyle">
              固定日期
              <a-range-picker
                :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')] }"
                format="YYYY-MM-DD HH:mm:ss"
                :placeholder="['开始日期', '结束日期']"
                :key="fixDateKey"
                @change="onFixDateChange"
                :defaultValue="defaultTime"
                :disabled="model.exipreType === 'get_last_day'"
              />
            </a-radio>
            <a-radio value="get_last_day" :style="radioStyle">
              领劵后
              <a-input-number
                v-model.trim="model.getValidDays"
                :min="0"
                :max="9999"
                :disabled="model.exipreType === 'fix_date'"
              />
              天生效，有效期
              <a-input-number
                v-model.trim="model.getEndDays"
                :min="0"
                :max="9999"
                :disabled="model.exipreType === 'fix_date'"
              />
              天
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="usePointsNum" label="积分换券">
          兑换一张券需要消费
          <a-input-number
            placeholder=""
            v-model.trim="model.usePointsNum"
            :disabled="!isEdit"
            :min="1"
            :max="999999"
            :formatter="limitNumber"
            :parser="limitNumber"
          />
          积分
        </a-form-model-item>
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useDesc" label="使用规则说明">
          <a-textarea placeholder="" v-model.trim="model.useDesc" style="width: 300px" :disabled="!isEdit" />
        </a-form-model-item>
        <a-divider />
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="prodScope" label="适用商品">
          <a-radio-group v-model="model.prodScope" @change="handelRadioProdScope('prodScope')" :disabled="!isEdit1">
            <a-radio :style="radioStyle" :value="0">全部商品</a-radio>
            <a-radio :style="radioStyle" :value="5"
              >按照分类(销售价尾数)
              <a-select
                v-model="model.priceTail"
                allowClear
                mode="multiple"
                :disabled="!isEdit1 || model.prodScope != 5"
              >
                <a-select-option v-for="(item, index) in priceTail" :key="index" :value="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-radio>
            <a-radio :style="radioStyle" :value="10">指定商品</a-radio>
          </a-radio-group>
          <div style="color: #f5222d">温馨提示：适用商品设置之后不能修改</div>
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
          <a-col :md="24" :sm="24">
            <a-form-model-item :wrapperCol="{ span: 5, offset: 5 }">
              <a-button type="primary" htmlType="submit" @click="handleOk" v-if="isEdit">保存优惠券</a-button>
              <a-button type="primary" htmlType="submit" @click="disabledForm(false)" v-else>编辑优惠券</a-button>
            </a-form-model-item>
          </a-col>
        </a-form-model-item>
      </a-form-model>
      <div
        class="ant-alert ant-alert-info"
        style="margin-bottom: 16px"
        v-if="model.prodScope == 0 || model.prodScope == 5"
      >
        排除商品设置说明：在下方添加排除商品，添加到排除商品列表里面的，不能使用优惠券下单。
      </div>
      <template v-if="childTab.visible">
        <a-tabs defaultActiveKey="1" style="margin-top: -15px">
          <a-tab-pane :tab="childTab.tabNm" key="1">
            <div class="table-operator">
              <a-button type="primary" @click="newRow">{{ childTab.btnNm }}</a-button>
            </div>
            <a-table
              :columns="columns"
              :dataSource="dataSource"
              size="middle"
              bordered
              rowKey="id"
              :pagination="ipagination"
              :loading="loading"
              class="j-table-force-nowrap"
              @change="handleTableChange"
            >
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm title="是否要删除此行？" @confirm="removeRow(record.id)"><a>删除</a></a-popconfirm>
              </template>
              <div slot="itemCodeFilterDropdown" style="padding: 8px">
              <a-input
                v-ant-ref="(c) => (searchInput = c)"
                v-model="queryParam.params.itemCode"
                style="width: 188px; margin-bottom: 8px; display: block"
              />
              <a-button size="small" style="width: 90px" @click="handleSearch()"> 查询 </a-button>
            </div>
            <a-icon slot="filterIcon" type="search" :style="{ color: '#108ee9' }" />
            <div slot="markPriceFilterDropdown" style="padding: 8px">
              <a-input-number
                v-ant-ref="(c) => (searchInputPrice = c)"
                v-model="queryParam.params.markPrice"
                :min="0"
                :max="999999"
                style="width: 188px; margin-bottom: 8px; display: block"
              />
              <a-button size="small" style="width: 90px" @click="handleSearch()"> 查询 </a-button>
            </div>
            </a-table>
          </a-tab-pane>
        </a-tabs>
        <SelectProductSpuList ref="selectSpuForm" @ok="selectOk"></SelectProductSpuList>
      </template>
    </a-card>
    </a-spin>
  </j-modal>
</template>

<script>
import { postAction, deleteAction } from '@/api/manage'
import moment from 'moment'
import { queryDepartTreeList1 } from '@/api/api'
import { limitNumber, filterObj } from '@/utils/util'
import SelectProductSpuList from './SelectProductSpuList'

export default {
  name: 'posMarketCouponModal',
  components: {
    SelectProductSpuList,
  },
  data() {
    return {
      moment,
      limitNumber,
      departModel: {
        departTreeOptions: [],
        orgIds: '',
        orgNames: '',
      },
      fieldNames: { label: 'title', value: 'value', children: 'children' },
      radioStyle: {
        display: 'block',
        height: '40px',
        lineHeight: '40px',
      },
      childTab: {
        tabNm: '可用商品设置',
        btnNm: '',
        visible: false,
        bizType: 1,
      },
      title: '操作',
      visible: false,
      fullscreen: true,
      isEdit: true,
      isEdit1: true,
      readonlyed: false,
      model: {},
      rangeDate: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      priceTail: [
        { text: '0', value: '0' },
        { text: '1', value: '1' },
        { text: '2', value: '2' },
        { text: '3', value: '3' },
        { text: '4', value: '4' },
        { text: '5', value: '5' },
        { text: '6', value: '6' },
        { text: '7', value: '7' },
        { text: '8', value: '8' },
        { text: '9', value: '9' },
      ],
      confirmLoading: false,
      validatorRules: {
        actNm: [{ required: true, message: '必填项' }],
        selecteddeparts: [{ required: true, message: '必填项' }],
        couponType: [{ required: true, message: '必填项' }],
        ruleVal: [{ required: true, message: '必填项' }],
        distTotal: [{ required: true, message: '必填项' }],
        exipreType: [{ required: true, message: '必填项' }],
        lessMoney: [{ required: true, message: '必填项' }],
        prodScope: [{ required: true, message: '必填项' }],
      },
      url: {
        add: '/marketing/posMarketAct/add',
        edit: '/marketing/posMarketAct/edit',
        listItemUrl: '/marketing/posGoodsSaleRule/listGoodsRuleItem',
        delItemUrl: '/marketing/posGoodsSaleRule/delete',
      },
      fixDateKey: new Date().toString(),
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
      searchText: '',
      searchInput: null,
      searchInputPrice: null,
      searchedColumn: '',
      columns: [
      {
          title: '品牌',
          dataIndex: 'brandName',
          width: 150,
        },
        {
          title: '商品名称',
          dataIndex: 'itemName',
          width: 600,
        },
        {
          title: '商品编码',
          dataIndex: 'itemCode',
          scopedSlots: {
            filterDropdown: 'itemCodeFilterDropdown',
            filterIcon: 'filterIcon',
          },
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              }, 0)
            }
          },
        },
        {
          title: '季节',
          dataIndex: 'itemSession',
        },
        {
          title: '类型',
          dataIndex: 'itemType',
        },
        {
          title: '零售价',
          dataIndex: 'markPrice',
          scopedSlots: {
            filterDropdown: 'markPriceFilterDropdown',
            filterIcon: 'filterIcon',
          },
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInputPrice.focus()
              }, 0)
            }
          },
        },
        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
    }
  },
  created() {
    this.loadDepartTree()
  },
  watch: {
    'model.exipreType': function (val) {
      console.log(val)
      if (val === 'fix_date') {
        this.$set(this.model, 'getValidDays', '')
        this.$set(this.model, 'getEndDays', '')
      } else {
        this.$set(this.model, 'startTime', '')
        this.$set(this.model, 'endTime', '')
        this.fixDateKey = new Date().toString()
      }
    },
  },
  computed: {
    defaultTime() {
      if (this.model.exipreType === 'get_last_day' || !this.model.startTime || !this.model.endTime) return []
      return [moment(this.model.startTime, 'YYYY-MM-DD HH:mm:ss'), moment(this.model.endTime, 'YYYY-MM-DD HH:mm:ss')]
    },
  },
  methods: {
    loadDepartTree() {
      let that = this
      queryDepartTreeList1({ orgTypes: '2' }).then((res) => {
        if (res.success) {
          that.$set(that.departModel, 'departTreeOptions', res.result)
          console.log('departTreeOptions', that.departModel.departTreeOptions)
          that.departModel.departTreeOptions.forEach((x) => {
            x['children'] = [{ title: '全部门店', value: '0' }]
          })
        }
      })
    },
    onDepartChange(value, selectedOptions) {
      console.log('value:', value)
      console.log('selectedOptions:', selectedOptions)
      this.departModel.orgIds = value && value.length > 0 ? value[0] : ''
      this.departModel.orgNames = selectedOptions && selectedOptions.length > 0 ? selectedOptions[0].departName : ''
    },
    newRow() {
      this.model.bizType = this.childTab.bizType
      this.$refs.selectSpuForm.search(this.departModel.orgIds, this.model)
      this.$refs.selectSpuForm.title = '选择商品'
      this.$refs.selectSpuForm.visible = true
    },
    removeRow(id) {
      deleteAction(this.url.delItemUrl, { id: id })
        .then((res) => {
          if (res.success) {
            this.$message.info(res.message)
            this.loadData(1)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    handleSearch() {
      this.loadData(1)
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize

      return filterObj(param)
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    selectOk(selectionRows) {
      console.log('selectionRows', selectionRows)
      this.loadData(1)
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    setVal() {
      console.log('selExpireType:', this.model.exipreType)
      if (this.model.exipreType === 'fix_date') {
        this.model.getValidDays = ''
        this.model.getEndDays = ''
      }
      if (this.model.id) {
        console.log('set selecteddeparts')
        this.$set(this.model, 'selecteddeparts', [this.model.scopeShopIds, '0'])

        console.log('this.model.lessMoney', this.model.lessMoney)

        this.isEdit = false

        console.log('bizStatus', this.model.bizStatus)

        if (this.model.bizStatus) {
          this.readonlyed = true
        } else {
          this.readonlyed = false
        }

        this.switchChildTab(this.model.prodScope)
      }
    },
    switchChildTab(prodScope) {
      this.childTab.visible = true
      let type = 1
      //0和1 排除商品和可用商品
      if (prodScope == 0 || prodScope == 5) {
        type = 0
      }
      this.childTab.bizType = type
      if (type == 0) {
        this.childTab.tabNm = '排除商品设置'
        this.childTab.btnNm = '添加排除商品'
      } else {
        this.childTab.tabNm = '可用商品设置'
        this.childTab.btnNm = '添加可用商品'
      }
      this.loadData(1)
    },
    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams() //查询条件

      console.log('params', params)

      this.loading = true
      postAction(this.url.listItemUrl, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || res.result
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    init() {
      this.model.actType = 50
      this.model.bizStatus = 0
      this.isEdit = true
      if (!this.model.exipreType) {
        console.log('set exipreType')
        this.$set(this.model, 'exipreType', 'fix_date')
      }

      if (!this.model.couponType) {
        console.log('set couponType')
        this.$set(this.model, 'couponType', 'mj')
      }
    },
    onFixDateChange: function (value, dateString) {
      this.model.startTime = dateString[0]
      this.model.endTime = dateString[1]
    },
    handelRadioProdScope(rule) {
      let selected = this.model[rule]
      if (selected == '0' || selected == '10') {
        this.$set(this.model, 'priceTail', [])
      }
    },
    add() {
      //初始化默认值
      this.edit({})
      this.init()
      this.readonlyed = false
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.visible = true

      if (record.id) {
        this.model.startTime = record.startTime
        this.isEdit1 = false

        this.$set(this.queryParam, 'params', { actId: this.model.id })
        this.$set(this.departModel, 'orgIds', this.model.scopeShopIds)
      } else {
        this.isEdit1 = true
      }
      this.setVal()
    },
    close() {
      this.clearAll()
      this.$emit('close')
      this.visible = false
      this.$refs.form.clearValidate()
    },
    clearAll() {
      this.model = {}
      this.childTab.visible = false
    },
    disabledForm(bool) {
      this.isEdit = !bool
    },
    checkParam(param) {
      let couponType = param.posMarketCouponInVo.couponType
      console.log('couponType', couponType)

      if (couponType === 'mj') {
        if (parseFloat(param.posMarketCouponInVo.lessMoney) <= parseFloat(param.posMarketCouponInVo.ruleVal)) {
          this.$message.warning('减免金额需小于使用门槛')
          return false
        }
      }
      return true
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.validExpireType()) {
            this.$message.warning('有效期不能为空')
            return false
          }

          let httpurl = ''
          if (!this.model.id) {
            httpurl += this.url.add
          } else {
            httpurl += this.url.edit
          }

          let reqVo = this.buildReqVo()
          if (!that.checkParam(reqVo)) {
            console.log('----check fail---')
            return false
          }
          that.confirmLoading = true

          postAction(httpurl, reqVo)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.confirmLoading = false
                that.isEdit1 = false
                that.model.id = res.result
                this.$set(this.queryParam, 'params', { actId: this.model.id })
                that.disabledForm(true)
                that.switchChildTab(that.model.prodScope)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              // that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
    buildReqVo() {
      let reqVo = {}

      reqVo.id = this.model.id
      reqVo.actNm = this.model.actNm
      reqVo.actType = this.model.actType
      reqVo.startTime = this.model.startTime
      reqVo.endTime = this.model.endTime
      reqVo.useDesc = this.model.useDesc
      reqVo.saveModal = 'MAIN'

      let prodScope = this.model.prodScope
      reqVo.prodScope = prodScope
      if (prodScope == '5') {
        let priceTail = this.model.priceTail
        if (!priceTail) {
          this.$message.warning('分类设置不能为空')
          res.success = false
          return res
        }
        reqVo.priceTail = priceTail
      }

      reqVo.actShops = [
        {
          orgId: this.model.selecteddeparts[0],
          orgType: 2,
          shopId: 0,
          useScope: 'ALL',
        },
      ]
      reqVo.posMarketCouponInVo = {}
      reqVo.posMarketCouponInVo.id = this.model.couponId
      reqVo.posMarketCouponInVo.actId = this.model.id
      reqVo.posMarketCouponInVo.couponType = this.model.couponType
      reqVo.posMarketCouponInVo.ruleVal = this.model.ruleVal
      reqVo.posMarketCouponInVo.exipreType = this.model.exipreType
      reqVo.posMarketCouponInVo.startTime = this.model.startTime
      reqVo.posMarketCouponInVo.endTime = this.model.endTime
      reqVo.posMarketCouponInVo.getValidDays = this.model.getValidDays
      reqVo.posMarketCouponInVo.getEndDays = this.model.getEndDays
      reqVo.posMarketCouponInVo.lessMoney = this.model.lessMoney
      reqVo.posMarketCouponInVo.reduceMax = this.model.reduceMax
      reqVo.posMarketCouponInVo.distTotal = this.model.distTotal
      reqVo.posMarketCouponInVo.usePointsNum = this.model.usePointsNum
      return reqVo
    },
    validExpireType() {
      if (this.model.exipreType === 'fix_date') {
        return this.model.startTime && this.model.endTime
      }
      console.log('---validExpireType---', this.model.exipreType)
      console.log('---getValidDays---', this.model.getValidDays)
      console.log('---getEndDays---', this.model.getEndDays)
      if (this.model.exipreType === 'get_last_day') {
        return this.model.getValidDays >= 0 && this.model.getEndDays > 0
      }
      return true
    },
  },
}
</script>

<style lang="less" scoped>

</style>